package com.sinothk.hussars.annotation.callback;

import com.sinothk.server.support.annotation.callback.BizException;
import com.sinothk.server.support.annotation.callback.ResponseResultAdvice;
import com.sinothk.server.support.entity.ResultCode;
import com.sinothk.server.support.entity.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;

/**
 * API统一返回引入：重写返回体 》 异常
 */
@Slf4j
@RestControllerAdvice
public class ResponseResultExceptionAdvice extends ResponseResultAdvice { // ResponseResultAdvice:自己定义

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = BizException.class)
    public ResultData bizExceptionHandler(BizException bizException) {
//        log.info("进入异常处理:{}", bizException);
        if (bizException.getResultCode() != null) {
            return ResultData.failure(bizException.getResultCode());
        }
        return ResultData.failure(bizException.getCode(), bizException.getMsg());
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultData HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
//        log.info("系统异常处理:{}", exception);
        String errorMsg = MessageFormat.format(ResultCode.SYS_INVALID_REQUEST_ERROR.message(), exception.getMethod(), exception.getSupportedHttpMethods());

        return ResultData.failure(ResultCode.SYS_INVALID_REQUEST_ERROR.code(), errorMsg);
    }

    /**
     * HttpRequestMethodNotSupportedException
     * 处理系统异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResultData exceptionHandler(Exception exception) {
//        log.info("系统异常处理:{}", exception);
        return ResultData.failure(4000, exception.getMessage());
    }

}
